import React, { useEffect, useState } from 'react';
import { connect, useDispatch, history } from 'umi';
import {
  Input,
  Button,
  Divider,
  message,
  Table,
  Popconfirm,
  Row,
  Col,
  Form,
  Modal,
  Alert,
} from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import PageTopFormContent from '@/components/PageTopFormContent';
import PaginationCommon from '@/components/PaginationCommon';
import RoleAddEdit from './components/RoleAddEdit';
import styles from './RoleManage.less';
import UsersSelect from './components/UserSelect';

const { confirm } = Modal;
const layout = {
  labelCol: { span: 8 },
  wrapperCol: { span: 16 },
};
const RoleManage = (props) => {
  const {
    commonRoleManageModel,
    common,
    loading: { effects },
  } = props;
  const { appCodeOfSelect } = common;
  const { roleList, roleListTotal } = commonRoleManageModel;

  const [currentPageNum, setCurrentPageNum] = useState(1);
  const [currentPageSize, setCurrentPageSize] = useState(10);
  const [sort, setSort] = useState();
  const [roleStateSearch, setRoleStateSearch] = useState();
  const [formData, setFormData] = useState({});
  const [currentEditData, setCurrentEditData] = useState({});
  const [drawerVisible, setDrawerVisible] = useState(false);
  const [selectedRows, setSelectedRows] = useState([]);
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [drawerType, setDrawerType] = useState('add');
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [listOfRoleUses, setListOfRoleUsers] = useState([]);
  const [editRole, setEditRole] = useState();

  const dispatch = useDispatch();
  const [form] = Form.useForm();

  useEffect(() => {
    const updateTableData = () => {
      const currentData = {
        pageIndex: currentPageNum,
        pageSize: currentPageSize,
        sortMap: sort,
        roleState: roleStateSearch,
        roleType: 0,
        appCode: appCodeOfSelect,
        ...formData,
      };
      dispatch({
        type: 'commonRoleManageModel/getRoleList',
        payload: currentData,
      });
    };
    if (appCodeOfSelect) updateTableData();
  }, [dispatch, currentPageNum, currentPageSize, formData, sort, roleStateSearch, appCodeOfSelect]);

  // const textRef = useRef();

  // useLayoutEffect(() => {
  //   textRef.current = text; // 将 text 写入到 ref
  // });

  const handleSearch = () => {
    const { validateFields } = form;
    validateFields().then((values) => {
      const param = { ...values };
      setFormData(param);
      setCurrentPageNum(1);
      resetSelection();
    });
  };

  const handleReset = () => {
    form.resetFields();
    setCurrentPageNum(1);
    setFormData({});
  };

  const handleShowEdit = (type, record) => {
    setDrawerType(type);
    setDrawerVisible(true);
    if (record) {
      setCurrentEditData(record);
    }
  };
  const handleCloseEdit = (updateFlag = false) => {
    setDrawerVisible(false);
    setCurrentEditData({});
    if (updateFlag) {
      handleSearch();
    }
  };

  const handleDel = (idsList) => {
    dispatch({
      type: 'commonRoleManageModel/deleteRole',
      payload: idsList,
    }).then((res) => {
      const { code, message: errMsg } = res;
      if (code === 0) {
        message.success('删除成功');
        handleSearch();
      } else {
        message.error(errMsg);
      }
    });
  };
  const handleBatchDel = () => {
    if (selectedRows.length > 0) {
      const roleNameList = [];
      const roleIdList = [];
      selectedRows.forEach((item) => {
        roleNameList.push(item.roleName);
        roleIdList.push(item.id);
      });
      confirm({
        title: `确定要批量删除：${
          roleNameList.length > 3
            ? `${roleNameList.slice(0, 3).join('、')}等`
            : roleNameList.join('、')
        }角色吗？`,
        onOk() {
          handleDel(roleIdList);
        },
      });
    } else {
      message.warn('请选择要删除的角色');
    }
  };

  const handleTableChange = (_, filters, sorter) => {
    const { roleState } = filters;
    if (JSON.stringify(sorter) !== '{}') {
      const { field, order } = sorter;
      setSort({ [field]: order === 'ascend' ? 'asc' : 'desc' });
    }
    if (roleState && roleState.length === 1) {
      setRoleStateSearch(roleState[0]);
    } else {
      setRoleStateSearch('');
    }
  };

  const handlePaginationChange = (page, pageSize) => {
    setCurrentPageNum(page);
    setCurrentPageSize(pageSize);
  };

  // const handleSetAuthConfigVisible = (visible, data) => {
  //   setAuthConfigVisible(visible);
  //   if (visible) {
  //     setCurrentEditData(data);
  //   } else {
  //     if (data) handleSearch();
  //     setCurrentEditData({});
  //   }
  // };

  const handleGoDetail = (record) => {
    history.push({
      pathname: '/authoritymanage/commonrolemanage/roledetail',
      state: {
        roleId: record.id,
      },
    });
  };

  // 授权用户确认操作
  const handOk = (selectUsers = []) => {
    dispatch({
      type: 'commonRoleManageModel/updateRole',
      payload: {
        ...editRole,
        appCode: appCodeOfSelect,
        userIdList: selectUsers.map((d) => d.userId),
      },
    }).then((res) => {
      const { code, message: errMsg } = res;
      if (code === 0) {
        message.success('操作成功');
        setListOfRoleUsers(selectUsers);
        setIsModalVisible(false);
        // 刷新列表
        const { validateFields } = form;
        validateFields().then((values) => {
          const param = { ...values };
          setFormData(param);
        });
      } else {
        message.error(errMsg);
      }
    });
  };

  // 授权用户操作
  const onAuthUser = (record) => {
    setEditRole(record);
    setIsModalVisible(true);
    dispatch({
      type: 'commonRoleManageModel/getRoleDtail',
      payload: { roleId: record.id },
    }).then((res) => setListOfRoleUsers(res?.data?.userList || []));
  };

  const columns = [
    {
      title: '角色编码',
      dataIndex: 'roleCode',
      key: 'roleCode',
      ellipsis: true,
    },
    {
      title: '角色名称',
      dataIndex: 'roleName',
      key: 'roleName',
      ellipsis: true,
    },
    {
      title: '用户数量',
      dataIndex: 'userCount',
      key: 'userCount',
      sorter: true,
    },
    {
      title: '描述',
      dataIndex: 'roleDesc',
      key: 'roleDesc',
      ellipsis: true,
    },
    {
      title: '创建人',
      dataIndex: 'creatorName',
      key: 'creatorName',
      ellipsis: true,
    },
    {
      title: '创建时间',
      dataIndex: 'gmtCreated',
      key: 'gmtCreated',
      width: 170,
      ellipsis: true,
      sorter: true,
    },
    {
      title: '更新人',
      dataIndex: 'modifierName',
      key: 'modifierName',
      ellipsis: true,
    },
    {
      title: '更新时间',
      dataIndex: 'gmtModified',
      width: 170,
      key: 'gmtModified',
      ellipsis: true,
      sorter: true,
    },
    {
      title: '操作',
      key: 'action',
      width: 250,
      fixed: 'right',
      render: (record) => (
        <div>
          <Button type="link" onClick={() => onAuthUser(record)}>
            授权用户
          </Button>
          <Divider type="vertical" />
          <Button type="link" onClick={() => handleShowEdit('edit', record)}>
            编辑
          </Button>
          <Divider type="vertical" />
          <Button type="link" onClick={() => handleGoDetail(record)}>
            详情
          </Button>
          <Divider type="vertical" />
          <Popconfirm title="确定要删除该角色吗？" onConfirm={() => handleDel([record.id])}>
            <Button type="link">删除</Button>
          </Popconfirm>
        </div>
      ),
    },
  ];

  const rowSelection = {
    selectedRowKeys,
    onChange: (selectedRowKeysParam, selectedRowsParam) => {
      setSelectedRowKeys(selectedRowKeysParam);
      setSelectedRows(selectedRowsParam);
    },
  };

  const resetSelection = () => {
    setSelectedRowKeys([]);
    setSelectedRows([]);
  };

  return (
    <div className={styles.root}>
      <PageTopFormContent
        title="公共角色管理"
        content={
          <Form {...layout} form={form} name="advanced_search">
            <Row gutter={[32, 16]}>
              <Col className="gutter-row" span={6}>
                <Form.Item name="roleCode" label="角色编码">
                  <Input placeholder="请输入角色编码" />
                </Form.Item>
              </Col>
              <Col className="gutter-row" span={6}>
                <Form.Item name="roleName" label="角色名称">
                  <Input placeholder="请输入角色名称" />
                </Form.Item>
              </Col>
              <Col className="gutter-row" span={12}>
                <Form.Item wrapperCol={{ ...layout.wrapperCol }}>
                  <Button type="primary" onClick={handleSearch}>
                    查询
                  </Button>
                  <Button style={{ marginLeft: 16 }} onClick={handleReset}>
                    重置
                  </Button>
                </Form.Item>
              </Col>
            </Row>
          </Form>
        }
      />
      <div className={styles.bottomWrapper}>
        <div className={styles.rightTableTop}>
          <div className={styles.title}>角色列表</div>
          <div className={styles.right}>
            {/* <Button onClick={handleBatchActive}>批量导入</Button> */}
            {selectedRowKeys.length !== 0 && (
              <Alert
                type="info"
                message={
                  <>
                    已选中 <strong>{selectedRowKeys.length}</strong> 条数据
                    <Button
                      type="link"
                      size="small"
                      onClick={() => {
                        resetSelection();
                      }}
                    >
                      清空
                    </Button>
                  </>
                }
                style={{ display: 'inline-block', padding: '3px 6px' }}
              />
            )}
            <Button onClick={handleBatchDel} type="danger" disabled={selectedRows.length === 0}>
              批量删除
            </Button>
            <Button type="primary" onClick={() => handleShowEdit('add')}>
              <PlusOutlined />
              新增
            </Button>
          </div>
        </div>
        <div className={styles.rightTable}>
          <div className={styles.tableWrapper}>
            <Table
              rowKey="id"
              loading={effects['commonRoleManageModel/getRoleList']}
              rowSelection={{
                ...rowSelection,
              }}
              columns={columns}
              dataSource={roleList}
              pagination={false}
              onChange={handleTableChange}
              scroll={{ x: 1280 }}
            />
            <PaginationCommon
              total={roleListTotal}
              onChange={handlePaginationChange}
              current={currentPageNum}
              pageSize={currentPageSize}
              style={{ textAlign: 'right' }}
            />
          </div>
        </div>
      </div>
      {drawerVisible && (
        <RoleAddEdit
          editData={currentEditData}
          appCodeOfSelect={appCodeOfSelect}
          drawerType={drawerType}
          handleClose={handleCloseEdit}
        />
      )}
      {isModalVisible && (
        <UsersSelect
          isModalVisible={isModalVisible}
          handOk={handOk}
          handleCancel={() => setIsModalVisible(false)}
          selectUsers={listOfRoleUses}
        />
      )}
    </div>
  );
};

export default connect((state) => state)(RoleManage);
